package com.dingding.manager.modules.order.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.dingding.manager.common.beans.order.SpecialOrderComment;
import com.dingding.manager.common.beans.order.UserOrder;
import com.dingding.manager.common.beans.order.UserSpecialOrder;
import com.dingding.manager.common.beans.order.UserSpecialOrdert;
import com.dingding.manager.common.beans.order.UserTaxiOrdert;
import com.dingding.manager.common.beans.passenger.UserDetail;
import com.dingding.manager.common.beans.sys.Organization;
import com.dingding.manager.common.dao.Page;
import com.dingding.manager.common.exception.BussinessException;
import com.dingding.manager.common.exception.enums.BizExceptionEnum;
import com.dingding.manager.core.shiro.ShiroKit;
import com.dingding.manager.core.util.ToolUtil;
import com.dingding.manager.modules.dirver.dto.ResDriverBasicInfoDTO;
import com.dingding.manager.modules.dirver.service.DriverManagerService;
import com.dingding.manager.modules.order.dao.IOrderDao;
import com.dingding.manager.modules.order.dto.ReqOrderDTO;
import com.dingding.manager.modules.order.dto.ResOrderDetailsDTO;
import com.dingding.manager.modules.order.dto.ResOrderListDTO;
import com.dingding.manager.modules.order.enums.OrderExceptionEnum;
import com.dingding.manager.modules.order.enums.OrderSetOutType;
import com.dingding.manager.modules.order.service.IOrderService;
import com.dingding.manager.modules.passenger.service.IPassengerService;
import com.dingding.manager.modules.system.service.OrganizationService;
import com.dingding.manager.modules.system.service.ProvinceAndCityService;

/**
 * 
 * @ClassName: OrderServiceImpl 
 * @Description: 订单相关的 service实现
 * @author hufan
 * @date 2016年12月8日 上午9:05:28 
 *
 */
@Service("orderService")
public class OrderServiceImpl implements IOrderService{

	@Resource(name="orderDao")
	IOrderDao orderDao;
	
	@Resource(name="organizationService")
	OrganizationService organizationService;

	@Resource(name="driverManagerService")
	DriverManagerService driverManagerService;
	
	@Resource(name="provinceAndCityService")
	ProvinceAndCityService provinceAndCityService;
	
	@Resource(name="passengerService")
	IPassengerService passengerService;
	
	/**
	 * 
	 * @Title: getOrderDTOListByPage 
	 * @Description: 分页查询订单列表
	 * @param reqOrderDTO
	 * @throws BussinessException  参数说明 
	 * @return List<ResOrderDTO>    返回类型 
	 * @throws
	 * sunzhicheng 添加数据范围（当前登录用户有权访问的公司）
	 */
	@Override
	@Transactional(readOnly=true)
	public Page<ResOrderListDTO> getOrderDTOListByPage(ReqOrderDTO reqOrderDTO) throws BussinessException {
		
		if(reqOrderDTO == null) {
			throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
		}
		//获取该用户现在可以查看的公司的id
		List<Integer> organizationIds = getOrganizationIds(reqOrderDTO);
		
		if(CollectionUtils.isEmpty(organizationIds)) {
			return new Page<ResOrderListDTO>(0, 0);
		}
		//查询条件（机构ids、前端输入的用户姓名或手机号码）进行司机id查询
		List<String> driverIds = driverManagerService.getDriverUserIdsByConditions(organizationIds,reqOrderDTO.getNameOrPhone());
		if(CollectionUtils.isEmpty(driverIds)) {
			return new Page<ResOrderListDTO>(0, 0);
		}
		Page<ResOrderListDTO> pageResult = orderDao.getResOrderDTOListByPage(driverIds, reqOrderDTO.getStatus(), reqOrderDTO.getTimeStart(), reqOrderDTO.getTimeEnd(), reqOrderDTO.getStart(), reqOrderDTO.getLength(),reqOrderDTO.getAddress());
		
		//处理其他数据
		this.dealOrderData(pageResult,reqOrderDTO);
		
		return pageResult;
	}
	
	/**
	 * 
	 * @Title: getOrderDetailsDTOByOrderId 
	 * @Description: 根据订单id查询订单详情
	 * @param orderId
	 * @param
	 * @param @throws BussinessException  参数说明 
	 * @return ResOrderDetailsDTO    返回类型 
	 * @throws
	 */
	@Override
	@Transactional(readOnly=true)
	public ResOrderDetailsDTO getOrderDetailsDTOByOrderId(String orderId) throws BussinessException {
		
		if(orderId == null) {
			throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
		}
		
		//由于不知道这条数据到底在那张表，需要根据订单id去四张表查询
		boolean isExist = false;//标记有没有查到，可以优化已查到订单信息还去其他表查询的不必要
		ResOrderDetailsDTO resOrderDetailsDTO = new ResOrderDetailsDTO();
		
		UserOrder userOrder = orderDao.getUserOrderByOrderId(orderId);
		if(userOrder != null) {
			BeanUtils.copyProperties(userOrder, resOrderDetailsDTO);
			isExist = true;
		}
		if(!isExist) {
			UserTaxiOrdert userTaxiOrdert = orderDao.getUserTaxiOrdertByOrderId(orderId);
			if(userTaxiOrdert != null) {
				BeanUtils.copyProperties(userTaxiOrdert, resOrderDetailsDTO);
				isExist = true;
			}
		}
		if(!isExist) {
			UserSpecialOrdert userSpecialOrdert = orderDao.getUserSpecialOrdertByOrderId(orderId);
			if(userSpecialOrdert != null) {
				BeanUtils.copyProperties(userSpecialOrdert, resOrderDetailsDTO);
				isExist = true;
			}
		}
		if(!isExist) {
			UserSpecialOrder userSpecialOrder = orderDao.getUserSpecialOrderByOrderId(orderId);
			if(userSpecialOrder != null) {
				BeanUtils.copyProperties(userSpecialOrder, resOrderDetailsDTO);
				isExist = true;
			}
		}
		
		if(!isExist) {
			throw new BussinessException(OrderExceptionEnum.ORDER_IS_NOT_EXIST.getCode(),OrderExceptionEnum.ORDER_IS_NOT_EXIST.getDesc());
		}
		
		//填充评论信息
		SpecialOrderComment specialOrderComment = orderDao.getSpecialOrderCommentByOrderId(orderId);
		if(specialOrderComment != null) {
			BeanUtils.copyProperties(specialOrderComment, resOrderDetailsDTO);
		}
		//填充司机信息
		ResDriverBasicInfoDTO resDriverBasicInfoDTO = driverManagerService.getResDriverBasicInfoDTOByDriverId(resOrderDetailsDTO.getGrabOrderUserId());
		if(resDriverBasicInfoDTO!=null) {
			resOrderDetailsDTO.setDriverName(resDriverBasicInfoDTO.getTrueName());
		}
		//填充乘客信息
		UserDetail userDetail = passengerService.getUserDetailByUserId(resOrderDetailsDTO.getPlaceOrderUserId());
		if(userDetail!=null) {
			resOrderDetailsDTO.setPassengerName(userDetail.getNickName());
			resOrderDetailsDTO.setPassengerPhone(userDetail.getTellphone());
		}
		return resOrderDetailsDTO;
	}

	/**
	 * 
	 * @Title: getOrganizationIds 
	 * @Description: 获取公司机构id
	 * @param @param reqOrderDTO
	 * @param @return  参数说明 
	 * @return List<Integer>    返回类型 
	 * @throws
	 * @date 2016/12/28 修改为通过登录用户的数据范围控制 获取当前登录用户有权限访问的机构
	 */
	public List<Integer> getOrganizationIds(ReqOrderDTO reqOrderDTO) {
		List<Integer> organizationIds = new ArrayList<Integer>();

		if (ToolUtil.isNotEmpty(reqOrderDTO.getCompanyId())) {
			organizationIds.add(reqOrderDTO.getCompanyId());
		}else{
			//获取当前用户有权访问的公司id
		      if(ToolUtil.isNotEmpty(reqOrderDTO.getProviceId())) {
		        organizationIds = organizationService.getOrganizationIds(reqOrderDTO.getProviceId(), reqOrderDTO.getCityId());
		      }else {
		        organizationIds = ShiroKit.getOrganizationIdList();
		      }
		}
		return organizationIds;
	}
	
	/**
	 * 
	 * @Title: dealOrderData 
	 * @Description: 填充没有的数据
	 * @param  参数说明 
	 * @author hufan
	 * @return 返回类型 
	 * @throws
	 */
	@Transactional(readOnly=true)
	public void dealOrderData(Page<ResOrderListDTO> pageResults,ReqOrderDTO reqOrderDTO) {
		//将没有的字段填充
		for (ResOrderListDTO resOrderDTO : pageResults.getList()) {
			Map<String, Object> driverInfo = orderDao.getOrderOtherInfoByDriverId(resOrderDTO.getGrabOrderUserId());
			if (driverInfo != null) {
				resOrderDTO.setTrueName((String) driverInfo.get("trueName"));
				resOrderDTO.setTelPhone((String) driverInfo.get("telPhone"));
				resOrderDTO.setOrganizationName((String) driverInfo.get("organizationName"));
				resOrderDTO.setProviceName((String)driverInfo.get("provinceName"));
				resOrderDTO.setCityName((String)driverInfo.get("cityName"));
			}
			
			//针对实时、预约进行处理
			Integer setOutType = resOrderDTO.getSetOutType();
			if(setOutType != null) {//只有专车有该字段
				if(setOutType == OrderSetOutType.SPECIAL_REALTIME_ORDER.getCode()) {//1:实时  2:预约
					resOrderDTO.setOrderType("专车实时单");
				}else if(setOutType == OrderSetOutType.SPECIAL_APPOINTMENT_ORDER.getCode()) {
					resOrderDTO.setOrderType("专车预约单");
				}
				//1:待指派  2:待上车(已指派)3:已上车  4:待支付(已到达) 5:已完成  6:已取消
				switch (resOrderDTO.getOrderStatus()) {
				case 2:
				case 3:
					resOrderDTO.setOrderStatus(2);
					break;
				case 4:
					resOrderDTO.setOrderStatus(3);
					break;
				case 5:
					resOrderDTO.setOrderStatus(4);
					break;
				case 6:
					resOrderDTO.setOrderStatus(5);
					break;
				default:
					break;
				}
			}else {//出租车
				resOrderDTO.setOrderType("出租车实时单");
				//1：待抢单  2：服务中 3：待支付 4：已完成 5：已取消
			}
		}
	}
}
